import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/login/widgets/underline_input_decorator.dart';
import 'package:flutter_syt/domain/widgets/code_form_field.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_comment.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/utils/web_socket_utility.dart';
import 'package:flutter_syt/widgets/common_button.dart';
import 'package:flutter_syt/widgets/dyt_aliyun_widget.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '/domain/login/widgets/login_protocol.dart';
import '../../global_common.dart';
import '../../global_easy_loading.dart';

@RoutePage(name: "resetPasswordPage")
class ResetPasswordPage extends StatefulWidget {
  const ResetPasswordPage();

  @override
  _ResetPasswordPageState createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> {
  final _formKey = GlobalKey<FormState>();

  // TextEditingController mobileController = new TextEditingController();

  // late PhoneWithAreaCodeEntity _phone;

  String _code = '', _password = '';

  bool _agree = false;

  Future<bool> getSmsCode() async {
    bool isVertifica = await UtilsOther.checkShowVertification(
        account: (UserInfo.me.registerType == '2'
                ? UserInfo.me.email
                : UserInfo.me.phone_number) ??
            '',
        // type: UserInfo.me.registerType == '2' ? '2' : '1',
        context: context,
        status: DytAliyunStatus.DytAliyunStatusMessage);
    if (isVertifica == false) {
      return false;
    }
    try {
      bool res = await (UserInfo.me.registerType == '2'
          ? API.shared.login
              .getEmailCode(UserInfo.me.email ?? '', 'reset-password')
          : API.shared.login.getPhoneCode2('reset-password'));
      return res;
    } catch (e) {
      await UtilsOther.showCustomShowError(e);
      // if (e is DioError) {
      //   customShowError(e.message);
      // } else {
      //   customShowError(S().network_error);
      // }
      return false;
    }
  }

  Future _submit() async {
    final form = _formKey.currentState;
    if (!_agree) {
      customShowToast(S.of(context).privacy_policy_consent_t);
      return;
    }
    if (form!.validate()) {
      form.save();
      try {
        bool res = await API.shared.user.password(_code, _password);
        if (res) {
          customShowSuccess(S.of(context).change_password_suss_login);
          try {
            if (await API.shared.user.logout()) {
              await GlobalData.unbindPush();
              // OnlineGlobalData.shared.clean();
              UserInfo.clean();
              WebSocketUtility.instance.closeSocket();
            }
          } catch (e) {}
          Navigator.of(context).popUntil((route) => route.isFirst);
          RouteManager.push(context, RoutMapping.loginByPwd());
          // RouteManager.push(context, RoutMapping.loginByPwd());
        } else {
          customShowError(S().network_error);
        }
      } catch (e) {
        await UtilsOther.showCustomShowError(e);
        // if (e is DioError) {
        //   customShowError(e.message);
        // } else {
        //   customShowError(S().network_error);
        // }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // UserInfo me = Provider.of<UserInfo>(context);
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).change_password,
        ),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: ClickUtils.debounce(() {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        }),
        child: Center(
          child: Container(
            // margin: EdgeInsets.only(top: 300),
            padding: EdgeInsets.all(20),
            child: Form(
              key: _formKey,
              child: Container(
                child: Column(
                  children: [
                    Container(
                        alignment: Alignment.centerLeft,
                        margin: EdgeInsets.only(bottom: 20),
                        child: Text(UserInfo.me.registerType == '2'
                            ? (UserInfo.me.email ?? '')
                            : UserInfo.me.phone_number)

                        // child: TextFormField(
                        //   // initialValue: me.nickname,
                        //   controller: TextEditingController(
                        //       text: UserInfo.me.registerType == '2'
                        //           ? (UserInfo.me.email ?? '')
                        //           : UserInfo.me.phone_number),
                        //   readOnly: true,
                        //   autofocus: false,
                        //   textAlign: TextAlign.left,
                        //   style: TextStyle(
                        //     color: ThemeColor.colorBlack100,
                        //     fontSize: 16,
                        //     height: 1.5,
                        //   ),
                        //   decoration: UnderlineInputDecoration(

                        //     prefixIcon: Container(
                        //       padding: EdgeInsets.only(
                        //         top: 0,
                        //         left: 0,
                        //         right: 5,
                        //         bottom: 0,
                        //       ),
                        //       margin: EdgeInsets.only(right: 10),
                        //       child: Text(me.phone_number),

                        //     ),
                        //   ),
                        //   obscureText: false,
                        // ),
                        ),
                    Container(
                      height: 1,
                      color: Colors.black.withOpacity(0.2),
                    ),
                    CodeFormField(
                      tagStr: 'resetpasswordpage',
                      // color: ThemeColor.colorBlack100,
                      suffixColor: Color(0xFF2942D1),
                      getSmsCode: getSmsCode,
                      decoration: UnderlineInputDecoration(),
                      onSaved: (val) => _code = val!,
                    ),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 1,
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 20),
                      child: TextFormField(
                        enableInteractiveSelection: true,
                        maxLength: 16,
                        inputFormatters: [
                          FilteringTextInputFormatter.deny(
                              appContext.emojiRegexp)
                        ],
                        autofocus: false,
                        style: TextStyle(
                          color: ThemeColor.colorBlack100,
                          fontSize: 16,
                        ),
                        cursorColor: ThemeColor.primaryColor,
                        decoration: UnderlineInputDecoration(
                          hintText: S.of(context).Password_8_16,
                        ),
                        validator: (val) {
                          if (val != null) {
                            if (!UtilsComment.checkPasswordFormal(val)) {
                              customShowToast(S.of(context).passwordToast_8_16);
                              return '';
                            }
                          }
                          return null;
                        },
                        onSaved: (val) => _password = val!,
                        obscureText: true,
                        // keyboardType: TextInputType.text,
                        keyboardType: TextInputType.visiblePassword,
                        autocorrect: false,
                      ),
                    ),
                    Container(
                      color: Colors.black.withOpacity(0.2),
                      height: 1,
                    ),
                    Container(
                      margin: const EdgeInsets.fromLTRB(10, 40, 10, 10),
                      width: double.infinity,
                      // child: ElevatedButton(
                      //     child: Text(
                      //       S.of(context).change_password_login,
                      //       style: TextStyle(fontWeight: FontWeight.bold),
                      //     ),
                      //     onPressed: ClickUtils.debounce(
                      //       () async {
                      //         await _submit();
                      //       },
                      //     )),
                      child: CommonButton.expend(
                        title: S().change_password_login,
                        onAsyncClick: () async {
                          await _submit();
                        },
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(left: 10),
                      width: double.infinity,
                      child: LoginProtocol(
                        color: ThemeColor.colorBlack100,
                        defaultCorol: ThemeColor.color979797,
                        onChange: (value) {
                          setState(() {
                            _agree = value;
                          });
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
